<template>

        <Card>
            <Row :gutter="20" class="margin-bottom-20">
                <i-col span="4">
                    <Select v-model="exceptionType">
                        <Option v-for="item in list" :value="item.type" :key="item.type">{{ item.description }}</Option>
                    </Select>
                </i-col>
                <i-col span="4">
                    <Select v-model="searchType" @on-change="handleRangeChange">
                        <Option :value="1">三个月内数据</Option>
                        <Option :value="2">三个月前数据</Option>
                    </Select>
                </i-col>
                <i-col span="8" v-if="searchType === 1">
                    <DatePicker
                        type="daterange"
                        :options="options"
                        placeholder="选择时间段"
                        style="width: 100%;"
                        v-model="timeRange"></DatePicker>
                </i-col>
                <i-col :span="8" v-if="searchType === 2">
                    <Row :gutter="20">
                        <i-col span="12">
                            <DatePicker
                                type="month"
                                format="yyyy年MM月"
                                placeholder="选择年月"
                                style="width:100%"
                                :options="optionsYearMonth"
                                @on-change="handleYearMonthChange"
                                v-model="timeLimt"></DatePicker>
                        </i-col>
                        <i-col span="12">
                            <DatePicker
                                type="daterange"
                                format="dd号"
                                :options="optionsMonth"
                                placeholder="选择时间段"
                                style="width: 100%;"
                                v-model="timeRange"></DatePicker>
                        </i-col>
                    </Row>
                </i-col>
                <Button type="primary" icon="ios-search" @click="getData(1)" :loading="isLoadig">搜索</Button>
            </Row>

            <br>
            <br>

            <!--表格数据-->
            <Table stripe border :columns="columns" :data="datas" size="small" :loading="isLoadig"></Table>
            <!--表格数据end-->

            <!--分页-->
            <Page :total="total"
            :page-size="size"
            show-elevator
            @on-change="getData"
            show-total style="text-align:center"></Page>
            <!--分页end-->
        </Card>

</template>

<script>
// import util from '@/libs/util';
import dayjs from 'dayjs'
import { http, api } from '@/libs/http'
import { AbnormalEvents } from '@/libs/const'
import { twoDaysAgo, now, startOfDay, endOfDay, generateShortcuts } from '@/libs/date'
export default {
  name: 'abnormal_report',
  props: {
    unnormalType: {
      // unnormalType: 1 门锁
      default: 'LOCK',
      required: true
    },
    room: {
      required: true
    }
  },
  data () {
    let columns1 = [
      {
        title: '异常时间',
        align: 'center',
        render (createElement, obj) {
          return createElement(
            'span', // 标签名称
            new Date(obj.row.time).Format('yyyy-MM-dd HH:mm')
          )
        }
      },
      {
        title: '异常类型',
        align: 'center',
        render (createElement, obj) {
          return createElement(
            'span', // 标签名称
            AbnormalEvents[obj.row.exception_type] || '未知'
          )
        }
      }
    ]
    const startOfThreeMonth = dayjs().subtract(3, 'month').startOf('month').valueOf()
    const endOfFourMonth = dayjs().subtract(4, 'month').endOf('month').valueOf()
    return {
      options: {
        shortcuts: generateShortcuts(),
        disabledDate (date) {
          return date && date.valueOf() < startOfThreeMonth
        }
      },
      optionsYearMonth: {
        disabledDate (date) {
          return date && date.valueOf() > endOfFourMonth
        }
      },
      searchType: 1,
      exportElemeter: 'export',
      isLoadig: false,
      size: 20,
      total: 0,
      baseColumns: columns1,
      roomInfo: {},
      datas: [],
      exceptionType: 0,
      timeLimt: '',
      timeRange: [twoDaysAgo, now]
    }
  },
  mounted () {
    this.getData(1)
  },
  computed: {
    columns () {
      const errorValueCol = [ 6, 7 ].includes(this.room.device_type)
        ? [{
          title: '异常值',
          align: 'center',
          render: (h, p) => {
            // paas手动获取的异常跟自动上传异常结构不同
            const paasResult = p.row.content && (p.row.content.detail || p.row.content.result)
            const value = paasResult && paasResult.amount
            const result = value ? `水表读数: ${value}` : ''
            return <span>{result}</span>
          }
        }]
        : []
      return [ ...this.baseColumns, ...errorValueCol ]
    },
    list () {
      return [{
        type: 0,
        description: '全部异常'
      }].concat(AbnormalEvents[this.unnormalType.toUpperCase()])
    },
    optionsMonth () {
      const timeLimt = this.timeLimt
      if (!timeLimt) return {}
      return {
        disabledDate (date) {
          const current = date && date.valueOf()
          if (!current) return false
          return dayjs(timeLimt).startOf('month').valueOf() > current || dayjs(timeLimt).endOf('month').valueOf() < current
        }
      }
    }
  },
  methods: {
    handleRangeChange (type) {
      this.timeRange = []
      if (type === 2) {
        const fourMonthAgo = dayjs().subtract(4, 'month')
        this.timeLimt = fourMonthAgo.toDate()
        this.timeRange = [fourMonthAgo.startOf('month').toDate(), fourMonthAgo.endOf('month').toDate()]
      }
    },
    handleYearMonthChange (date) {
      this.timeRange = [dayjs(this.timeLimt).startOf('month').toDate(), dayjs(this.timeLimt).endOf('month').toDate()]
    },
    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
          this.getData(1) // 获取第一页全部数据
        }
      })
    },
    getData (page) {
      // 找出deviceId
      const { roomId, id: device_id } = this.room
      const params = {
        limit: this.size,
        offset: this.size * (page - 1),
        start_time: startOfDay(this.timeRange[0]),
        end_time: endOfDay(this.timeRange[1])
      }
      if (this.searchType === 2 && this.timeLimt) {
        params.year = this.timeLimt.getFullYear()
        params.month = this.timeLimt.getMonth() + 1
      }
      if (this.exceptionType) {
        params.exception_type = this.exceptionType
      }
      this.isLoadig = true
      http.request(this, api.room_exceptions_info, [roomId, device_id], params, res => {
        if (res) {
          this.datas = res.exceptions
          this.total = res.count || 0
        }
        this.isLoadig = false
      })
    }
  }
}
</script>

<style lang="less">
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
</style>